package easyway.trainapp.webframework.util;

import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

public class FileService {
	public void downloadFile(HttpServletResponse response, String realName, String fileName) throws IOException { 
	    fileName = java.net.URLEncoder.encode(fileName, "UTF-8");//解决中文文件名的问题

	  response.setHeader("Content-disposition", 
	                "attachment; filename=" + fileName); 
	  	        
	     //   response.setContentType("application/x-download"); 
	  	if(fileName.endsWith(".pdf")){
	  		response.setContentType("application/pdf;charset=UTF-8");
	  	}
	  	else if(fileName.endsWith(".doc")){
	  		response.setContentType("application/msword;charset=UTF-8");
	  	}
	  	else if(fileName.endsWith(".xls")){
	  		response.setContentType("application/msexcel;charset=UTF-8");
	  	}else{
	  		response.setContentType("application/x-download;charset=UTF-8");
	  	}
	        //File exportFile = new File(realName); 
	        //response.setContentLength((int) exportFile.length()); 
	        ServletOutputStream servletOutputStream = response.getOutputStream(); 
	        byte[] b = new byte[1024]; 
	        int i = 0; 
	        FileInputStream fis = new java.io.FileInputStream(realName); 
	        while ((i = fis.read(b)) > 0) { 
	            servletOutputStream.write(b, 0, i); 
	            servletOutputStream.flush();
	        } 
	        fis.close(); 
	        servletOutputStream.close();
	    } 
}
